package com.nl.countdownclock.client;
import com.nl.countdownclock.client.Ball;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Date;

public class PhysicalEnsemble {
	// hack connection to MatrixDigit by using a singleton
	static PhysicalEnsemble theEnsemble = null;
	public PhysicalEnsemble(){
		theEnsemble = this;
		
	}
	private ArrayList<Ball> balls = new ArrayList<Ball>();
	double g = 1.0;
	
	static PhysicalEnsemble getPhysicalEnsemble(){
		return theEnsemble;
		
	}
	
	public void add(Ball b){
		balls.add(b);
		double now = ((double)(new Date()).getTime())/1000.0;
		b.setTime(now);
	}
	public void evolve(){
		// take each ball and bring it current in time 
		double now = ((double)(new Date()).getTime())/1000.0;
		evolve( now);
	}
	public void evolve(double t){
		// take each ball and evolve it until time t
		ArrayList<Ball> todelete = new ArrayList<Ball>();
		ListIterator<Ball> iter = balls.listIterator();
		while(iter.hasNext()){
			Ball b = iter.next();
			if( evolve(b, t))
				todelete.add(b);
		}
		balls.removeAll(todelete);
	}
	public ListIterator<Ball> getIterator(){
		return balls.listIterator();
	}
	
	
	private boolean evolve( Ball b, double t){ // return true if ball out of bounds
		double deltat = t - b.getTime();
		// vx changes with a collision  --- add later
		double vy, vx, x, y;
		vy = b.vy;
		vx = b.vx;
		x = b.x;
		y = b.y;
		vy = vy + g * deltat;
		x = x + vx * deltat;
		y = y + vy * deltat;
		b.x = x;
		b.y = y;
		b.vy = vy;
		
		// temporary hack to remove lost balls
		// should have less arbitrary universe bounds set in constructor
		if ( b.x < -3000.0 || b.x > 3000.0  || b.y < -3000.0 || b.y > 3000.0 )
			return true;
		else
			return false;
		
	}
}
